import type { ILovItemQuery } from "@/types"
import { queryLovInfo } from "@/api/common"

export default async function useLov (lovList: ILovItemQuery[]) {
  const result: Record<string, { value: string, label: string }> = {}
  const noCacheLovList = []
  for (const lovItem of lovList) {
    const cacheKey = `${lovItem.moduleName}.${lovItem.paramKey}`
    const cacheRes = localStorage.getItem(cacheKey)
    if (cacheRes) {
      result[lovItem.paramKey] = JSON.parse(cacheRes)
    } else {
      noCacheLovList.push(lovItem)
    }
  }
  if (noCacheLovList.length) {
    const { data } = await queryLovInfo(noCacheLovList)
    if (data.success && data.object) {
      Object.keys(data.object).forEach(moduleName => {
        Object.keys(data.object[moduleName]).forEach(paramKey => {
          const lovRes = data.object[moduleName][paramKey].map((i: { option_key: string; option_desc: string }) => ({
            value: i.option_key,
            label: JSON.parse(i.option_desc)['zh_CN']
          }))
          result[paramKey] = lovRes
          const cacheKey = `${moduleName}.${paramKey}`
          localStorage.setItem(cacheKey, JSON.stringify(lovRes))
        })
      })
    }
  }

  return result
}